const NewsModel = require('../../models/NewsModel');
const UserModel = require('../../models/UserModel');
// 新闻服务
const NewsService = {
  // 获取新闻列表
  list: async ({ page = 1, pageSize = 10 }) => {
    let result = await NewsModel.find(
      {
        isDelete: false,
      },
      ['title', 'content', 'category', 'author', 'cover', 'editorType', 'isTop', 'isPublish', 'updateTime', 'createTime']
    )
      .limit(pageSize)
      .skip((page - 1) * pageSize);
    // 返回总条数
    const count = await NewsModel.countDocuments({
      isDelete: false,
    });
    // 将result中的author全部转换为user表中的username，使用Promise.all优化异步操作
    const promises = result.map(async el => {
      try {
        let user = await UserModel.findById(el.author, ['username']).catch(error => console.error(error));
        if (user) {
          el.author = user.username;
        } else {
          el.author = '未知';
        }
        return el;
      } catch (error) {
        console.error('Error processing news items:', error);
        return el; // Ensure the original element is returned in case of an error
      }
    });

    await Promise.all(promises); // 确保所有异步操作完成
    return { row: result, count: count };
  },
  // 获取新闻详情
  findById: async _id => {
    const result = await NewsModel.findById(_id, ['title', 'content', 'category', 'author', 'cover', 'editorType']);
    return result;
  },
  // 创建新闻
  add: async data => {
    const result = await NewsModel.create(data);
    return result;
  },
  // 更新新闻
  edit: async (_id, data) => {
    const result = await NewsModel.updateOne({ _id }, { ...data, updateTime: new Date() });
    if (result.nModified === 0) {
      return false;
    } else {
      // 查询出最新数据返回
      const result = await NewsModel.findById(_id, ['title', 'content', 'category', 'author', 'cover', 'editorType', 'isTop', 'isPublish', 'updateTime', 'createTime']);
      return result;
    }
  },
  // 删除新闻
  delete: async _id => {
    const result = await NewsModel.updateOne(
      { _id },
      {
        isDelete: true,
      }
    );
    return result;
  },
  // 发布新闻  and 停止发布
  publish: async (_id, isPublish) => {
    const result = await NewsModel.updateOne(
      { _id },
      {
        isPublish: isPublish,
        updateTime: new Date(), // 更新编辑时间
      }
    );
    return result;
  },
  // 取消置顶
  isTop: async (_id, isTop) => {
    const result = await NewsModel.updateOne(
      { _id },
      {
        isTop: isTop,
        updateTime: new Date(), // 更新编辑时间
      }
    );
    return result;
  },
};

module.exports = NewsService;
